package com.deuwise.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;
import com.deuwise.common.utils.cache.Cache;
import com.deuwise.common.validator.ValidatorUtils;
import com.deuwise.common.validator.group.AddGroup;
import com.deuwise.common.validator.group.UpdateGroup;
import com.deuwise.system.entity.SysRole;
import com.deuwise.system.service.SysRoleMenuService;
import com.deuwise.system.service.SysRoleService;

import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 *@author deuwise
 *@date 2018-11-06 14:15:04
 */
@Api(tags = "角色模块", description = "角色模块")
@RequestMapping("api/sys/role")
@RestController()
@RequiresAuthentication
public class SysRoleController extends  AbstractController {
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 角色列表
     */
    @ApiOperation("获取角色list")
    @GetMapping("/list")
    @RequiresPermissions("sys:role:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleName", value = "角色名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    public Result<Page<SysRole>> list(@RequestParam(value = "roleName",required = false) String roleName) {

        Wrapper<SysRole> wrapper = new EntityWrapper<>();
        if (roleName!=null&&StringUtils.isNotBlank(roleName)) {
            wrapper.like("role_name", roleName);
        }
        wrapper.ne("invented",1);
        wrapper.orderBy("create_time",false);
        Page<SysRole> page = sysRoleService.selectPage(getPage(SysRole.class), wrapper);

        return Result.ok(page);
    }


    /**
     * 角色信息
     */
    @ApiOperation("角色详情")
    @GetMapping("/{roleId}")
    @RequiresPermissions("sys:role:info")
    public R info(@PathVariable("roleId") String roleId) {
        SysRole role = sysRoleService.selectById(roleId);

        //查询角色对应的菜单
        List<String> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
        role.setMenuIdList(menuIdList);

        return R.ok().put("role", role);
    }

    /**
     * 保存角色
     */
    @ApiImplicitParam(name = "role", value = "角色对象", required = true, dataType = "SysRole", paramType = "body")
    @ApiOperation("新增角色")
    @PostMapping("")
    @RequiresPermissions("sys:role:save")
    public R save(@RequestBody SysRole role) {
        role.setId(null);
        ValidatorUtils.validateEntity(role, AddGroup.class);
        int count = sysRoleService.queryByName(role.getRoleName(),null);
        if (count > 0) {
            return R.error(200, "角色名称不能重复");
        }
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        role.setCreateAt(getUserId());
        sysRoleService.save(role);
        return R.ok();
    }

    /**
     * 修改角色
     */
    @ApiOperation("修改角色")
    @PutMapping("")
    @ApiImplicitParam(name = "role", value = "角色对象", required = true, dataType = "SysRole", paramType = "body")
    @RequiresPermissions("sys:role:update")
    public R update(@RequestBody SysRole role) {
        ValidatorUtils.validateEntity(role, UpdateGroup.class);
        int count = sysRoleService.queryByName(role.getRoleName(),role);
        if (count > 0) {
            return R.error(200, "角色名称不能重复");
        }
        role.setUpdateTime(new Date());
        sysRoleService.update(role);
        Cache.removeLike("permsSet");
        return R.ok();
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/{id}")
    @RequiresPermissions("sys:role:delete")
    public R delete(@PathVariable("id") String id) {
        try {
            sysRoleService.deleteById(id);

        } catch (Exception ex) {
            return R.error("删除失败");
        }
        return R.ok();
    }


    @ApiOperation(value = "批量删除记录")
    @RequiresPermissions("sys:role:delete")
    @RequestMapping(value = "/deleteSelect", method = RequestMethod.POST)
    public  R deleteSelect(@ApiParam(value = "ids集合",name = "ids",required = true) @RequestParam String[] ids){
        try {
            if (ids != null && ids.length > 0) {
                sysRoleService.deleteBatchIds(Arrays.asList(ids));
            }
        }catch (Exception ex){
            return  R.error("删除失败");
        }
        return  R.ok();
    }

}